#include "Timer.h"

module SerialC @safe()
{
    uses interface Timer<TMilli> as Timer;
    uses interface SplitControl as Control;
    uses interface Leds;
    uses interface Boot;
    uses interface AMSend;
    uses interface Packet;
}
implementation
{
    uint16_t counter;
    message_t buffer;

    task void incrementCounter();
    task void handleFire();

    event void Boot.booted()
    {
        counter = 0;
        call Control.start();
    }

    event void Control.startDone(error_t err)
    {
        if (err == SUCCESS)
        {
            call Timer.startPeriodic( 1024 );
        }
    }

    // Do nothing
    event void Control.stopDone(error_t err) {}

    event void Timer.fired()
    {
        post incrementCounter();
        post handleFire();
    }

    event void AMSend.sendDone(message_t * msg, error_t err)
    {
        if (err != SUCCESS)
        {
            call Leds.set(7);
        }
        //call Leds.set(4);
    }

    task void incrementCounter() { counter += 1; }

    task void handleFire()
    {
        serial_msg_t* payload = (serial_msg_t*)call Packet.getPayload(&buffer, sizeof(serial_msg_t));
        payload->counter = counter;
        call Leds.set(payload->counter % 4);

        call Leds.set(payload->counter % 4);
        
        if (call AMSend.send(AM_SERIAL_MSG, &buffer, sizeof(serial_msg_t)) != SUCCESS)
        {
            call Leds.set(7);
            post handleFire();
        }  
    }
}

